const express = require('express');
const customerInfoModel = require('../models/customerInfo');
const { Message,MessageList } = require('../utils/message');

const router = express.Router();

//获取用户详细信息
router.get('/', (req, res, next) => {
  const {username,name} = req.query;
  const queryObj={}
  let {page=1,pageSize=10}=req.query
  let regexp=new RegExp(name,'i');
  if(username) queryObj.username=username;
  if(name) queryObj.$or=[{name:{$regex:regexp}}];
  page=Number(page)
  pageSize=Number(pageSize)
  customerInfoModel.find(queryObj).count((err,total)=>{
    customerInfoModel.find(queryObj).limit(pageSize).skip((page-1)*pageSize).then(data=>{
        res.json(MessageList(200,'',data,page,pageSize,total))
      })
  })
});

router.get('/findOne',(req,res,next)=>{
  const {username}=req.query;
  customerInfoModel.findOne({username}).then(data => {
    if(data){
      res.json(Message(200,'',data))
    }else{
      res.json(Message(400,'未查找到数据！'))
    }
  })
})

//修改用户信息
router.put('/', (req, res,next) => {
  // const {username} = req.params;
  const {username, nickname, sex, name, phone,address,brand,model,color,carId} = req.body;
  customerInfoModel.updateOne({username}, {nickname,name, sex, phone,address,carInfo:{brand,model,color,carId}}).then(data => {
    if(data.modifiedCount !== 0){
      res.json({
        code: 200,
        data: {
          status: 200,
          message: '修改成功！'
        }
      })
    }else if(data.modifiedCount === 0&&data.matchedCount!==0){
      res.json({
        code: 200,
        data: {
          status: 400,
          message: '修改失败，未修改任何数据！'
        }
      })
    }else if(data.modifiedCount===0&&data.matchedCount===0){
      res.json({
        code: 200,
        data: {
          status: 400,
          message: '修改失败，没有该数据！'
        }
      })
    }
  })
})

//修改用户信息
router.put('/userType', (req, res,next) => {
  // const {username} = req.params;
  const {username,userType,discount} = req.body;
  customerInfoModel.updateOne({username}, {userType,discount}).then(data => {
    if(data.modifiedCount !== 0){
      res.json({
        code: 200,
        data: {
          status: 200,
          message: '开通成功！'
        }
      })
    }else if(data.modifiedCount === 0&&data.matchedCount!==0){
      res.json({
        code: 200,
        data: {
          status: 400,
          message: '开通失败！'
        }
      })
    }else if(data.modifiedCount===0&&data.matchedCount===0){
      res.json({
        code: 200,
        data: {
          status: 400,
          message: '开通失败！'
        }
      })
    }
  })
})



module.exports = router;